const vscode = require("vscode");
const { Converter } = require("opencc-js");

let statusBarItem;
let converter;

function activate(context) {
    console.log("简繁转换插件已激活");

    // 初始化 OpenCC 转换器（简体转繁体）
    converter = Converter({ from: "cn", to: "tw" });

    // 创建状态栏项目
    statusBarItem = vscode.window.createStatusBarItem(
        vscode.StatusBarAlignment.Right,
        100
    );
    statusBarItem.command = "simplifiedToTraditional.convert";

    // 更新状态栏显示
    updateStatusBar();

    // 监听配置变化
    context.subscriptions.push(
        vscode.workspace.onDidChangeConfiguration((e) => {
            if (e.affectsConfiguration("simplifiedToTraditional.enabled")) {
                updateStatusBar();
            }
        })
    );

    // 注册转换命令
    const convertCommand = vscode.commands.registerCommand(
        "simplifiedToTraditional.convert",
        () => {
            convertText();
        }
    );

    context.subscriptions.push(convertCommand, statusBarItem);
}

function updateStatusBar() {
    const config = vscode.workspace.getConfiguration("simplifiedToTraditional");
    const enabled = config.get("enabled", true);

    if (enabled) {
        statusBarItem.text = "$(globe) 转为繁体";
        statusBarItem.tooltip = "点击将当前文档的简体中文转换为繁体中文";
        statusBarItem.show();
    } else {
        statusBarItem.hide();
    }
}

async function convertText() {
    const config = vscode.workspace.getConfiguration("simplifiedToTraditional");
    const enabled = config.get("enabled", true);

    if (!enabled) {
        vscode.window.showInformationMessage(
            "简繁转换功能已禁用，请在设置中启用"
        );
        return;
    }

    const editor = vscode.window.activeTextEditor;
    if (!editor) {
        vscode.window.showWarningMessage("请先打开一个文件");
        return;
    }

    const document = editor.document;
    const selection = editor.selection;

    try {
        // 显示进度条
        await vscode.window.withProgress(
            {
                location: vscode.ProgressLocation.Notification,
                title: "正在转换简体中文为繁体中文...",
                cancellable: false,
            },
            async (progress) => {
                progress.report({ increment: 0 });

                if (selection.isEmpty) {
                    // 如果没有选中文本，转换整个文档
                    const fullText = document.getText();
                    const convertedText = converter(fullText);

                    progress.report({ increment: 50 });

                    const fullRange = new vscode.Range(
                        document.positionAt(0),
                        document.positionAt(fullText.length)
                    );

                    await editor.edit((editBuilder) => {
                        editBuilder.replace(fullRange, convertedText);
                    });

                    progress.report({ increment: 100 });
                    vscode.window.showInformationMessage("文档转换完成！");
                } else {
                    // 转换选中的文本
                    const selectedText = document.getText(selection);
                    const convertedText = converter(selectedText);

                    progress.report({ increment: 50 });

                    await editor.edit((editBuilder) => {
                        editBuilder.replace(selection, convertedText);
                    });

                    progress.report({ increment: 100 });
                    vscode.window.showInformationMessage("选中文本转换完成！");
                }
            }
        );
    } catch (error) {
        console.error("转换错误:", error);
        vscode.window.showErrorMessage(`转换失败: ${error}`);
    }
}

function deactivate() {
    if (statusBarItem) {
        statusBarItem.dispose();
    }
}

module.exports = {
    activate,
    deactivate,
};
